"""
用户管理路由
"""
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional

from database import get_db
from auth import get_current_active_user, AuthHandler
from models import User, Wallet
from schemas import UserResponse, UserUpdate, BaseResponse, PaginatedResponse, ChangePasswordRequest

router = APIRouter()

@router.get("/me", response_model=UserResponse)
async def get_my_info(
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户信息"""
    return current_user

@router.put("/me", response_model=UserResponse)
async def update_my_info(
    user_data: UserUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新当前用户信息"""
    # 检查邮箱是否已被其他用户使用
    if user_data.email and user_data.email != current_user.email:
        existing_user = db.query(User).filter(
            User.email == user_data.email,
            User.id != current_user.id
        ).first()
        if existing_user:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="邮箱已被其他用户使用"
            )
    
    # 更新用户信息
    update_data = user_data.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(current_user, field, value)
    
    db.commit()
    db.refresh(current_user)
    
    return current_user

@router.get("/{user_id}", response_model=UserResponse)
async def get_user_info(
    user_id: int,
    db: Session = Depends(get_db)
):
    """获取指定用户信息"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    if user.status != 'active':
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在或已被禁用"
        )
    
    return user

@router.get("/", response_model=PaginatedResponse)
async def get_users(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),

    keyword: Optional[str] = Query(None, description="搜索关键词"),
    db: Session = Depends(get_db)
):
    """获取用户列表（分页）"""
    query = db.query(User).filter(User.status == 'active')
    

    
    # 关键词搜索
    if keyword:
        query = query.filter(
            (User.username.contains(keyword)) | 
            (User.nickname.contains(keyword)) |
            (User.email.contains(keyword))
        )
    
    # 分页
    total = query.count()
    users = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=users,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )



@router.get("/me/favorites", response_model=PaginatedResponse)
async def get_my_favorites(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户的收藏列表"""
    # 导入Favorite和Product模型
    from models import Favorite, Product
    
    # 查询当前用户收藏的商品
    query = db.query(Product).join(Favorite).filter(
        Favorite.user_id == current_user.id,
        Product.status == 'available'
    )
    
    # 分页
    total = query.count()
    favorites = query.offset((page - 1) * size).limit(size).all()
    
    return PaginatedResponse(
        items=favorites,
        total=total,
        page=page,
        size=size,
        pages=(total + size - 1) // size
    )

@router.get("/me/wallet", response_model=dict)
async def get_my_wallet(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取当前用户钱包信息"""
    wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
    if not wallet:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="钱包不存在"
        )
    
    return {
        "balance": float(wallet.balance),
        "user_id": wallet.user_id,
        "updated_at": wallet.updated_at
    }

@router.post("/me/wallet/deposit", response_model=BaseResponse)
async def deposit_to_wallet(
    amount: float = Query(..., ge=0.01, description="充值金额"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """钱包充值"""
    wallet = db.query(Wallet).filter(Wallet.user_id == current_user.id).first()
    if not wallet:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="钱包不存在"
        )
    
    # 更新余额
    wallet.balance += amount
    db.commit()
    
    return BaseResponse(message=f"充值成功，当前余额：{wallet.balance:.2f}")

@router.delete("/me", response_model=BaseResponse)
async def delete_my_account(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除当前用户账户"""
    # 检查是否有未完成的交易
    from models import Trade
    active_trades = db.query(Trade).filter(
        (Trade.buyer_id == current_user.id) | (Trade.seller_id == current_user.id),
        Trade.status.in_(['pending_payment', 'paid', 'shipped'])
    ).count()
    
    if active_trades > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="存在未完成的交易，无法删除账户"
        )
    
    # 软删除用户（标记为inactive）
    current_user.status = 'inactive'
    db.commit()
    
    return BaseResponse(message="账户删除成功")